﻿using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using doubango_rt.BackEnd;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using WinRT.SIP.UILogic.Repositories;

namespace WinRT.SIP.UILogic.ViewModels
{
    public class DialerPageViewModel : ViewModel, ITextMessageListener, ICallListener
    {
        private readonly IDoubangoServer _server = null;
        private readonly CoreDispatcher _dispatcher;
        private string _phoneNumber;
        private string _textMessage;
        private string _sendTextMessage;

        public string PhoneNumber
        {
            get { return _phoneNumber; }
            set { SetProperty(ref _phoneNumber, value); }
        }

        public string TextMessage
        {
            get { return _textMessage; }
            set { SetProperty(ref _textMessage, value); }
        }

        public string SendTextMessage
        {
            get { return _sendTextMessage; }
            set { SetProperty(ref _sendTextMessage, value); }
        }

        public string CallerName { get; set; }

        public DelegateCommand GoBackCommand { get; private set; }
        public DelegateCommand DialOneCommand { get; private set; }
        public DelegateCommand DialTwoCommand { get; private set; }
        public DelegateCommand DialThreeCommand { get; private set; }
        public DelegateCommand DialFourCommand { get; private set; }
        public DelegateCommand DialFiveCommand { get; private set; }
        public DelegateCommand DialSixCommand { get; private set; }
        public DelegateCommand DialSevenCommand { get; private set; }
        public DelegateCommand DialEightCommand { get; private set; }
        public DelegateCommand DialNineCommand { get; private set; }
        public DelegateCommand DialAsteriskCommand { get; private set; }
        public DelegateCommand DialZeroCommand { get; private set; }
        public DelegateCommand DialPoundCommand { get; private set; }
        public DelegateCommand CallCommand { get; private set; }
        public DelegateCommand AnswerCommand { get; private set; }
        public DelegateCommand TextCommand { get; private set; }
        public DelegateCommand DeleteCommand { get; private set; }

        public DialerPageViewModel(ICallRepository currentCallRepository, INavigationService navigationService, IDoubangoServer server)
        {
            // Set the sip server to use
            _server = server;

            GoBackCommand = new DelegateCommand(navigationService.GoBack, () => { return false; });

            DialOneCommand = new DelegateCommand(() => PhoneNumber += "1");
            DialTwoCommand = new DelegateCommand(() => PhoneNumber += "2");
            DialThreeCommand = new DelegateCommand(() => PhoneNumber += "3");
            DialFourCommand = new DelegateCommand(() => PhoneNumber += "4");
            DialFiveCommand = new DelegateCommand(() => PhoneNumber += "5");
            DialSixCommand = new DelegateCommand(() => PhoneNumber += "6");
            DialSevenCommand = new DelegateCommand(() => PhoneNumber += "7");
            DialEightCommand = new DelegateCommand(() => PhoneNumber += "8");
            DialNineCommand = new DelegateCommand(() => PhoneNumber += "9");
            DialAsteriskCommand = new DelegateCommand(() => PhoneNumber += "*");
            DialZeroCommand = new DelegateCommand(() => PhoneNumber += "0");
            DialPoundCommand = new DelegateCommand(() => PhoneNumber += "#");

            CallCommand = new DelegateCommand(() =>
            {
                if (!String.IsNullOrEmpty(PhoneNumber))
                {
                    currentCallRepository.SetCurrentCallee(PhoneNumber, false);
                    navigationService.Navigate("Call", null);
                }
            });

            AnswerCommand = new DelegateCommand(() =>
            {
                currentCallRepository.SetCurrentCallee(CallerName, true);
                navigationService.Navigate("Call", null);                  
            });

            TextCommand = new DelegateCommand(async () =>
            {
                if (!string.IsNullOrEmpty(PhoneNumber) && !string.IsNullOrEmpty(SendTextMessage))
                {
                    await MakeTextAsync(PhoneNumber, SendTextMessage);
                }
            });

            DeleteCommand = new DelegateCommand(() =>
            {
                if (!String.IsNullOrEmpty(PhoneNumber))
                {
                    PhoneNumber = PhoneNumber.Substring(0, PhoneNumber.Length - 1);
                }
            });

            _dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

            _server.Instance.SipService.SetTextMessageListener(this);
            currentCallRepository.SetCallListener(this);
        }

        public void OnTextMessageReceived(string message)
        {
            _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => TextMessage = message); 
        }

        public void OnIncommingCall(string callerName)
        {
            CallerName = callerName;
            _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => AnswerCommand.Execute()); 

        }

        public async Task MakeTextAsync(string phoneNumber, string textMessage)
        {
            await Task.Run(() =>
            {
                var sipService = _server.Instance.SipService;

                if (sipService != null && sipService.RegistrationState == SipSessionState.Connected)
                {
                    rtSipUri toUri = _server.Instance.rtSipUriNew(string.Format("sip:{0}@sip2sip.info", phoneNumber), "unknown");
                    var messageSession = sipService.SetupMessagingSession(toUri, null);
                    messageSession.addHeader("Content-Type", ContentType.TEXT_PLAIN);
                    sipService.SendMessage(messageSession, textMessage);
                }
            });
        }
    }
}
